package com.starfactory.customer.config;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.StringCodec;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.StringUtils;

/**
 */
@Configuration
public class RedisConfig {

    private static final String REDIS_PREFIX = "redis://";
    private static final String COLON = ":";


    @Value("${spring.redis.host}")
    private String redisHost;

    @Value("${spring.redis.port}")
    private String redisPort;

    @Value("${spring.redis.password}")
    private String redisPassword;

    @Value("${spring.redis.database}")
    private Integer redisDatabase;

    @Value("${spring.redis.timeout}")
    private Integer redisTimeout;

    @Bean
    RedissonClient redissonClient() {
        Config config = new Config();
        config.useSingleServer().setAddress(REDIS_PREFIX + redisHost + COLON + redisPort);
        if (!StringUtils.isEmpty(redisPassword)) {
            config.useSingleServer().setPassword(redisPassword);
        }
        config.useSingleServer().setDatabase(redisDatabase);
        config.useSingleServer().setTimeout(redisTimeout);
        config.setCodec(new StringCodec());
        return Redisson.create(config);
    }


    @Bean
    public RedisSerializer<String> springSessionDefaultRedisSerializer() {
        return new StringRedisSerializer();
    }

}
